import json
from datetime import datetime

from django.http import JsonResponse
from django.views import View
from django.core.paginator import Paginator

from user.models import SysUser
from user.serializers import SysUserSerializer
from role.models import SysRole, SysUserRole

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny  # ✅ 暂时关闭权限

@method_decorator(csrf_exempt, name='dispatch')  # ✅ 跳过 CSRF 验证（与之前一致）
class SearchView(APIView):

    def post(self, request):
        print("✅ SearchView 触发")

        data = request.data  # ✅ 使用 DRF 提供的数据解析
        pageNum = data.get('pageNum')
        pageSize = data.get('pageSize')
        query = data.get('query', '')

        try:
            user_qs = SysUser.objects.filter(username__icontains=query).order_by('id')
            paginator = Paginator(user_qs, pageSize)
            userListPage = paginator.page(pageNum)

            obj_users = userListPage.object_list.values()
            users = list(obj_users)

            for user in users:
                userId = user['id']
                roleList = SysRole.objects.raw(
                    f"SELECT id, NAME FROM sys_role WHERE id IN "
                    f"(SELECT role_id FROM sys_user_role WHERE user_id={userId})"
                )
                roleListDict = [{"id": role.id, "name": role.name} for role in roleList]
                user['roleList'] = roleListDict

            total = user_qs.count()

            return Response({'code': 200, 'userList': users, 'total': total})

        except Exception as e:
            print("❌ SearchView 错误：", e)
            return Response({'code': 500, 'msg': '查询失败', 'error': str(e)})

@method_decorator(csrf_exempt, name='dispatch')  # ✅ 跳过 CSRF（测试阶段）
class ActionView(APIView):

    def get(self, request):
        user_id = request.GET.get("id")
        try:
            user = SysUser.objects.get(id=user_id)  # 🟰 获取用户
            serializer = SysUserSerializer(user)    # 🟰 序列化
            return Response({'code': 200, 'user': serializer.data})  # 🔁 用 DRF Response 返回
        except SysUser.DoesNotExist:
            return Response({'code': 404, 'msg': '用户不存在'})  # ✅ 增加错误处理

    def delete(self, request):
        id_list = request.data  # 🔁 使用 DRF 的 request.data，无需 decode
        if not isinstance(id_list, list):
            return Response({'code': 400, 'msg': '请求格式错误，应为用户ID数组'})  # ✅ 新增校验
        SysUserRole.objects.filter(user_id__in=id_list).delete()
        SysUser.objects.filter(id__in=id_list).delete()
        return Response({'code': 200})

@method_decorator(csrf_exempt, name='dispatch')  # ✅ 跳过 CSRF
class CheckView(APIView):

    def post(self, request):
        username = request.data.get('username')
        print("✅ 接收到 username:", username)

        if SysUser.objects.filter(username=username).exists():
            return Response({'code': 500})  # ✅ 已存在
        else:
            return Response({'code': 200})  # ✅ 可用

@method_decorator(csrf_exempt, name='dispatch')  # ✅ 跳过 CSRF
class PasswordView(APIView):

    def get(self, request):
        user_id = request.GET.get("id")
        try:
            user = SysUser.objects.get(id=user_id)
            user.password = "123456"  # ✅ 这里是明文密码（后期记得改成加密）
            user.update_time = datetime.now().date()
            user.save()
            return Response({'code': 200, 'msg': '密码重置成功'})
        except SysUser.DoesNotExist:
            return Response({'code': 404, 'msg': '用户不存在'})

@method_decorator(csrf_exempt, name='dispatch')  # ✅ 跳过 CSRF（测试阶段）
class StatusView(APIView):
    permission_classes = [AllowAny]  # ✅ 暂时放开权限限制

    def post(self, request):
        data = request.data  # ✅ DRF 推荐写法
        user_id = data.get('id')
        status = data.get('status')

        if not user_id or status is None:
            return Response({'code': 400, 'msg': '缺少参数'})

        try:
            user = SysUser.objects.get(id=user_id)
            user.status = status
            user.save()
            return Response({'code': 200, 'msg': '状态更新成功'})
        except SysUser.DoesNotExist:
            return Response({'code': 404, 'msg': '用户不存在'})



